#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Author    : jltxseo
# @File      : forms.py
# @Time      : 18年3月15日 下午9:45
# @Software  : PyCharm
# @Desc      :
import re
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, ValidationError, PasswordField, TextAreaField
from wtforms.validators import DataRequired, Length, EqualTo
from app.base.models import User


class CommentForm(FlaskForm):
    """
    Form vaildator for comment.
    """
    name = StringField('Name', validators=[DataRequired(), Length(max=255)])

    text = StringField(u'Comment', validators=[DataRequired()])


class LoginForm(FlaskForm):
    """
    Login Form
    """
    username = StringField('账号', validators=[DataRequired(), Length(max=255)])
    password = PasswordField('密码', validators=[DataRequired()])

    def validate(self):
        """Validator for check the account information."""
        check_validata = super(LoginForm, self).validate()

        # If validator no pass
        if not check_validata:
            return False

        # Check the user whether exist.
        user = User.query.filter_by(username=self.username.data).first()
        if not user:
            self.username.errors.append('Invalid username or password.')
            return False

        # Check the password whether right.
        if not user.check_password(self.password.data):
            self.username.errors.append('Invalid username or password.')
            return False

        return True


class RegisterForm(FlaskForm):
    """Register Form."""

    username = StringField('账号', [DataRequired('请输入账号'), Length(max=255)])
    password = PasswordField('密码', [DataRequired('请输入密码'), Length(min=6)])
    comfirm = PasswordField('确认密码', [DataRequired('请输入确认密码'), EqualTo('password')])
    recaptcha = RecaptchaField()

    def validate(self):
        check_validate = super(RegisterForm, self).validate()

        # If validator no pass
        if not check_validate:
            return False

        # Check the user whether exist.
        user = User.query.filter_by(username=self.username.data).first()
        if user:
            self.username.errors.append('User with that name already exists.')
            return False
        return True


class PostForm(FlaskForm):
    """Post Form."""

    title = StringField('Title', [DataRequired(), Length(max=255)])
    test = TextAreaField('Blog Content', [DataRequired()])


def custom_email(form_object, field_object):
    """Define a vaildator"""
    if not re.match(r"[^@+@[^@]+\.[^@]]+", field_object.data):
        raise ValidationError('Field must be a valid email address.')
